package com.tanhua.server.serivce;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.ContractVo;
import com.tanhua.domain.vo.MessageLikeVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务类，封装业务操作，专门给控制器使用
 */
@Service
public class IMService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private FriendApi friendApi;
    @Reference
    private CommentApi commentApi;

    /**
     * 接口名称：回复陌生人问题
     * 注意：消息格式固定
     * {"userId": "1","nickname":"黑马兄弟","strangerQuestion": "你喜欢去爬山吗？",
     * "reply": "我喜欢秋天的落叶，夏天的泉水，冬天的雪地，以及雄伟的大山~"}
     */
    public ResponseEntity<Object> replyQuestion(Long userId, String reply) {
        // 根据用户id查询
        UserInfo userInfo = userInfoApi.findById(userId);
        // 根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);

        // 构造消息内容，格式固定（前端取值是按照这个格式）
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userInfo.getId().toString());
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", question==null?"你喜欢我吗.？":question.getTxt());
        map.put("reply", reply);

        // map转换为string
        String msgString = JSON.toJSONString(map);

        // 发送消息
        huanXinTemplate.sendMsg(userId.toString(),msgString);
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：联系人添加
     */
    public ResponseEntity<Object> addContract(long friendId) {
        //0. 获取登陆用户id
        Long userId = UserHolder.getUserId();

        //1. 保存好友关系到tanhua_users表
        friendApi.save(userId,friendId);

        //2. 保存好友关系到环信中
        huanXinTemplate.contactUsers(userId,friendId);
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：联系人列表
     * 查询的表：
     *    tanhua_users
     *          userId  登陆用户id
     *          friendId 联系人列表（好友列表 ）
     */
    public ResponseEntity<Object> contractList(Integer page, Integer pagesize, String keyword) {
        Long userId = UserHolder.getUserId();
        //1. 调用api分页查询
        PageResult pageResult = friendApi.findByPage(userId,page,pagesize);

        //2. 获取分页数据
        List<Friend> friendList = (List<Friend>) pageResult.getItems();

        //3. 封装返回的vo集合： friendList--->voList
        List<ContractVo> voList = new ArrayList<>();
        if (friendList != null) {
            for (Friend friend : friendList) {
                // 根据好友用户的id，查询用户信息
                UserInfo userInfo = userInfoApi.findById(friend.getFriendId());
                // 创建并封装vo
                ContractVo vo = new ContractVo();
                BeanUtils.copyProperties(userInfo,vo);

                vo.setUserId(userInfo.getId().toString());
                vo.setCity(StringUtils.substringBefore(vo.getCity(),"-"));

                voList.add(vo);
            }
        }

        //4. 设置vo集合到分页对象
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：点赞/评论/喜欢 列表
     * 接口路径：GET/messages/likes(comments)(loves)
     */
    public ResponseEntity<Object> querylikesList(int commentType, Integer page, Integer pagesize) {
        //1. 查询当前登陆用户相关的评论；【当前用户不是评论人，是被评论人；被评论人其实就是发布者】
        PageResult pageResult =
                commentApi.findCommentsByPublishUserId(UserHolder.getUserId(),commentType,page,pagesize);
        //2. 获取评论数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();
        //3. 构造返回的结果数据
        List<MessageLikeVo> result = new ArrayList<>();
        //4. 遍历查询的评论数据，封装返回结果
        if (commentList != null && commentList.size()>0) {
            commentList.forEach((comment -> {
                MessageLikeVo messageLikeVo = new MessageLikeVo();
                // 根据评论人用户id查询
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                if(userInfo != null) {
                    BeanUtils.copyProperties(userInfo,messageLikeVo);
                    messageLikeVo.setId(comment.getId().toHexString());
                    String createDate = new SimpleDateFormat("yyyy-MM-dd").format(userInfo.getCreated());
                    messageLikeVo.setCreateDate(createDate);
                    result.add(messageLikeVo);
                }
            }));
        } //5. 设置集合到分页对象中
        pageResult.setItems(result);
        return ResponseEntity.ok(pageResult);
    }
}
